package com.newenergy.wisehome.ui.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.MyEvent;
import com.newenergy.wisehome.common.helper.AppInfoHelper;
import com.newenergy.wisehome.common.helper.LogHelper;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.config.Constants;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.bean.FamilyUnique;
import com.newenergy.wisehome.data.bean.Icon;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyUniqueDao;
import com.newenergy.wisehome.data.ormlite.dao.IconDao;
import com.newenergy.wisehome.ui.fragment.BaseFragment;
import com.newenergy.wisehome.ui.fragment.FragmentHelper;
import com.newenergy.wisehome.ui.widget.CustomDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;
import me.yokeyword.fragmentation.SupportActivity;

//import static com.newenergy.fivesmart.config.AppManager.mCurrFamily;

public abstract class BaseActivity extends SupportActivity {

    private static final String TAG = "QBH";

    private BluetoothAdapter mBleAdapter;
    public boolean isShowAllLight = true;
    private Toast mToast;
    private CustomDialog mCustomDialog;


    private ArrayList<PermissionItem> mPermissonItems;
    private Unbinder mBind;
    private boolean mSpeechEnable=getSpeechEnable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        init();
        ininListen();
        initState();

    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config=new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config,res.getDisplayMetrics() );
        return res;
    }

    protected abstract int getLayoutId();

    protected abstract void ininListen();

    protected void init() {
        mBind = ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initPermissonItems();
        checkMutiPermission(this);
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        initBle();
        registerReceiver(mReceiver, makeFilter());
        initDBDao();

        int versionCode = AppInfoHelper.getVersionCode(this);
        if (versionCode<=5 ){
            DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(this);
            List<DeviceCategory> heaIfModelNull = deviceCategoryDao.getHEAIfModelNull();
            if (heaIfModelNull != null && heaIfModelNull.size() > 0) {
                deviceCategoryDao.delete(heaIfModelNull);
            }
        }
    }


    /**
     * 沉浸式状态栏
     */
    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }


    private void initDBDao() {
        if (!isFirstInit()) {
            getAppIdWithBleMac();
            Family family = CreatDefault();
            AppManager.getInstance(this).mCurrFamily=family;
            SPUtil.put(Constants.FIRST_INIT, true);
            SPUtil.put(Constants.ISDELETEDEFAULTFAMILY, true);
        } else {
            checkFamilyUnique();
            if (!isHadDeleteDefaultFamily()) {
                DeleteDefaultFamily();
                SPUtil.put(Constants.ISDELETEDEFAULTFAMILY, true);
            }


        }

    }


    private void checkFamilyUnique() {
        FamilyUniqueDao uniqueDao = new FamilyUniqueDao(this);
        FamilyDao familyDao = new FamilyDao(this);
        List<FamilyUnique> uniques = uniqueDao.getAll();
        if (uniques.size() > 0) {
            for (FamilyUnique unique : uniques) {
                if (unique.getSeed() <= 0) {
                    Family family = familyDao.getById(unique.getFamilyId());
                    int seed = family != null ? family.getSeed() : getSeed(unique.getFamilyId());
                    int feedBack = family != null ? family.getFeedback() : getFeedBack();
                    unique.setSeed(seed);
                    unique.setFeedback(feedBack);
                }
                uniqueDao.update(unique);
            }
        }
    }


    //创建默认的家庭以及默认的房间，使用默认的家庭码
    private Family CreatDefault() {
        FamilyDao familyDao = new FamilyDao(this);
        BallLightDao ballLightDao = new BallLightDao(this);
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(this);
        FamilyUniqueDao uniqueDao = new FamilyUniqueDao(this);

        FamilyUnique unique = uniqueDao.getByType(0);

        unique.setType(1);
        uniqueDao.update(unique);

        String familyId = unique.getFamilyId();
        int seed = unique.getSeed();
        int feedBack = unique.getFeedback();

        SPUtil.put("FAMILY_ID", familyId);
        Family family=new Family(familyId,getString(R.string.happy_family),5,seed,feedBack);
        familyDao.add(family);
        String scenedata1 = familyId + "01"+ "FF000000"  + "FFFFFF";
        String scenedata2 = familyId + "02"+ "FF000000"  + "FFFFFF";
        String scenedata3 = familyId + "03"+ "FF000000"  + "FFFFFF";
        String scenedata4 = familyId + "04"+ "FF000000"  + "FFFFFF";
        String scenedata5 = familyId + "05"+ "FF000000"  + "FFFFFF";
        BallLight ballLight1 =new BallLight(familyId,1,"01",getString(R.string.master_bedroom),"zhu wo","btn_balllight",scenedata1);
        BallLight ballLight2 =new BallLight(familyId,1,"02",getString(R.string.second_bedroom),"ci wo","btn_balllight",scenedata2);
        BallLight ballLight3 =new BallLight(familyId,1,"03",getString(R.string.kitchen),"chu fang","btn_balllight",scenedata3);
        BallLight ballLight4 =new BallLight(familyId,1,"04",getString(R.string.living_room),"ke ting","btn_balllight",scenedata4);
        BallLight ballLight5 =new BallLight(familyId,1,"05",getString(R.string.restaurant),"can ting","btn_balllight",scenedata5);
        ballLightDao.add(ballLight1);
        ballLightDao.add(ballLight2);
        ballLightDao.add(ballLight3);
        ballLightDao.add(ballLight4);
        ballLightDao.add(ballLight5);
        DeviceCategory deviceCategory1 = ballLight1.covertToDeviceCategory();
        DeviceCategory deviceCategory2 = ballLight2.covertToDeviceCategory();
        DeviceCategory deviceCategory3 = ballLight3.covertToDeviceCategory();
        DeviceCategory deviceCategory4 = ballLight4.covertToDeviceCategory();
        DeviceCategory deviceCategory5 = ballLight5.covertToDeviceCategory();
        deviceCategoryDao.add(deviceCategory1);
        deviceCategoryDao.add(deviceCategory2);
        deviceCategoryDao.add(deviceCategory3);
        deviceCategoryDao.add(deviceCategory4);
        deviceCategoryDao.add(deviceCategory5);
        return family;

    }

    private void initPermissonItems() {
        mPermissonItems = new ArrayList<>();
        mPermissonItems.add(new PermissionItem(Manifest.permission
                .RECORD_AUDIO,
                getString(R.string.recording), R.drawable.permission_ic_micro_phone));
        mPermissonItems.add(new PermissionItem(Manifest.permission
                .CAMERA,
                getString(R.string.camera), R.drawable.permission_ic_camera));
        mPermissonItems.add(new PermissionItem(Manifest.permission
                .WRITE_EXTERNAL_STORAGE,  getString(R.string.sd),
                R.drawable.permission_ic_storage));
        mPermissonItems.add(new PermissionItem(Manifest.permission
                .READ_PHONE_STATE,
                getString(R.string.phone_status), R.drawable.permission_ic_phone));
        mPermissonItems.add(new PermissionItem(Manifest.permission
                .ACCESS_COARSE_LOCATION,
                getString(R.string.location), R.drawable.permission_ic_location));
    }

    protected void initIcons() {
        IconDao iconyDao = new IconDao(this);
        //清空图片
        iconyDao.deleAll();

        //客厅 厨房，餐厅 卧室，阳台，卫生间，
        //客厅
        iconyDao.add(new Icon("icon_living_room", 1));
        //餐厅
        iconyDao.add(new Icon("icon_dining_room", 1));
        //厨房
        iconyDao.add(new Icon("icon_kitchen", 1));
        //卧室
        iconyDao.add(new Icon("icon_bedroom", 1));
        //阳台
        iconyDao.add(new Icon("icon_balcony1", 1));
        //卫生间
        iconyDao.add(new Icon("icon_lavatory", 1));

        //场景
        iconyDao.add(new Icon("icon_romantic1", 2));//浪漫
        iconyDao.add(new Icon("icon_romantic2", 2));//浪漫
        iconyDao.add(new Icon("icon_paty1", 2));//聚会
        iconyDao.add(new Icon("icon_reading", 2));//阅读
        iconyDao.add(new Icon("icon_movie", 2));//阅读
        iconyDao.add(new Icon("icon_game", 2));//游戏
        iconyDao.add(new Icon("icon_music", 2));//音乐

    }

    private String getBleMac() {
        String bleAddress ="";
        if (Build.VERSION.SDK_INT >= 23) {
              bleAddress = android.provider.Settings.Secure.getString(this.getContentResolver(),"bluetooth_address");
        }else {
            bleAddress = BluetoothAdapter.getDefaultAdapter().getAddress();

        }
        if (TextUtils.isEmpty(bleAddress)){
            int[] nums = randomCommon(1, 255, 6);
            StringBuilder builder = new StringBuilder();
            for (int i=0;i<6;i++){
                String hexString = Integer.toHexString(nums[i]);
                hexString= hexString.length()<2?'0'+hexString:hexString;
                builder.append(hexString);
                if (i<5){
                    builder.append(":");
                }
            }
            bleAddress=builder.toString().toUpperCase();
        }
        return bleAddress;

    }



    /**
     * 随机指定范围内N个不重复的数
     * 最简单最基本的方法
     * @param min 指定范围最小值
     * @param max 指定范围最大值
     * @param n 随机数个数
     */
    public  int[] randomCommon(int min, int max, int n){
        if (n > (max - min + 1) || max < min) {
            return null;
        }
        int[] result = new int[n];
        int count = 0;
        while(count < n) {
            int num = (int) (Math.random() * (max - min)) + min;
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if(num == result[j]){
                    flag = false;
                    break;
                }
            }
            if(flag){
                result[count] = num;
                count++;
            }
        }
        return result;
    }

    public boolean isFirstInit() {
        return SPUtil.getBool(Constants.FIRST_INIT, false);
    }

    public boolean isHadDeleteDefaultFamily() {
        return SPUtil.getBool(Constants.ISDELETEDEFAULTFAMILY, false);
    }

    private void initBle() {
        BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        mBleAdapter = bluetoothManager.getAdapter();
    }

    /**
     * 请求打开蓝牙
     */
    private void openBleRequest() {
        if (mBleAdapter != null) {
            if (!mBleAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter
                        .ACTION_REQUEST_ENABLE);
                enableBtIntent.setFlags(Intent
                        .FLAG_ACTIVITY_NEW_TASK);
                startActivity(enableBtIntent);
            }
        } else {
            Log.i("blueTooth", "该手机不支持蓝牙");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mBind.unbind();
        unregisterReceiver(mReceiver);
        SPUtil.put(Constants.ISDOWNLOAD,false);

    }


    public void showFragment(Class<? extends BaseFragment> fragmentClass, Object data) {
        FragmentHelper.replaceFragment(this, R.id.main_container,fragmentClass, data);

    }

    public void toast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }


    private int dp2px(Context context, int size) {
        return (int) (context.getResources().getDisplayMetrics()
                .density * size);
    }


    /**
     * 监听蓝牙快关状态
     */
    private IntentFilter makeFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        return filter;
    }


    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra
                            (BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_TURNING_ON:
                            break;
                        case BluetoothAdapter.STATE_ON:
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:

                            break;
                        case BluetoothAdapter.STATE_OFF:
//                            openBleRequest();
                            break;
                    }
                    break;
            }
        }
    };


    private void getAppIdWithBleMac() {
        FamilyUniqueDao uniqueDao = new FamilyUniqueDao(this);
        String bleAddress = getBleMac();
        String[] macs = bleAddress.split(":");
        if (macs.length == 6) {
            String hexs=  (macs[3] + macs[4] + macs[5]).toUpperCase();
            for (int i = 1; i <=5 ; i++) {
                String hex = intToHex(i);
                String familyId = hex + hexs;
                int seed = getSeed(familyId);
                int feedBack = getFeedBack();
                FamilyUnique familyUnique = new FamilyUnique(familyId, 0, feedBack, seed);
                uniqueDao.add(familyUnique);
            }
        }

        List<FamilyUnique> uniques = uniqueDao.getAll();
        for (FamilyUnique unique : uniques) {
            LogHelper.i("unique=" + unique);
        }
    }


    //为版本小于3.00.03的添加多两个家庭
    private void getAppIdWithBleMacInLowVersion() {
        FamilyUniqueDao uniqueDao = new FamilyUniqueDao(this);
        String bleAddress = getBleMac();
        String[] macs = bleAddress.split(":");
        if (macs.length == 6) {
            String hexs=  (macs[3] + macs[4] + macs[5]).toUpperCase();
            for (int i = 4; i <=5 ; i++) {
                String hex = intToHex(i);
                String familyId = hex + hexs;
                int seed = getSeed(familyId);
                int feedBack = getFeedBack();
                FamilyUnique familyUnique = new FamilyUnique(familyId, 0, feedBack, seed);
                uniqueDao.add(familyUnique);
            }
        }

        List<FamilyUnique> uniques = uniqueDao.getAll();
        for (FamilyUnique unique : uniques) {
            LogHelper.i("unique=" + unique);
        }

    }



    private String intToHex(int num2) {
        String hex = Integer.toHexString(num2).toUpperCase();
        if (hex.length() < 2) hex = "0" + hex;
        return hex;
    }


    /**
     * 获取加密种子
     * @param familyId 传入的家庭id
     * @return 加密种子
     */
    private int getSeed(String familyId) {
        String stringSeed = subString(familyId, 0, 2);
        if (stringSeed.equals("00")) {
            stringSeed = "0A";
        }
        return Integer.parseInt(stringSeed, 16);
    }


    /**
     * 获取反馈参数
     * @return 反馈参数
     */
    private int getFeedBack() {
        Random random = new Random();
        int randata;
        do {
            randata = random.nextInt(65535);
        } while (CheckRule(randata) == 0);
        return randata;
    }


    /**
     * 截取指定位置指定长度的字符串
     * @param content 传入的字符串
     * @param start 开始位置
     * @param length 长度
     * @return 截取后的字符
     */
    private String subString(String content, int start, int length) {
        return content.substring(start, start + length);
    }

    private void checkMutiPermission(Context context) {
        HiPermission.create(context.getApplicationContext())
            .title(getString(R.string.permission_application))
            .permissions(mPermissonItems)
            .filterColor(ResourcesCompat.getColor(getResources
                    (), R.color.colorPrimary, getTheme()))//图标的颜色
            .msg(getString(R.string.voice_requires_permissions))
            .style(R.style.PermissionBlueStyle)
            .checkMutiPermission(new PermissionCallback() {
                @Override
                public void onClose() {
                    Log.i(TAG, "onClose");
                    toast(getString(R.string.user_closure_application));
                }

                @Override
                public void onFinish() {
//                        toast("所有权限申请完成");
                    Log.e("LFX", "所有权限申请完成");
                    if (mSpeechEnable||!isServiceRunning()){
//                        Intent intent = new Intent(BaseActivity.this, BaiDuService.class);
//                        startService(intent);
                    }

                }

                @Override
                public void onDeny(String permisson, int
                        position) {
                    Log.i(TAG, "onDeny:permisson=" + permisson);
                }

                @Override
                public void onGuarantee(String permisson, int
                        position) {
                    Log.i(TAG, "onGuarantee:permisson=" +
                            permisson + "  position=" + position);
                }
            });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }


    /**
     * 判断语音是否被禁用
     *
     * @return
     */
    public boolean getSpeechEnable() {
        return SPUtil.getBool(Constants.SPEECH_ENABLE, false);
    }

    public void setSpeechEnable(boolean enable) {
        SPUtil.put(Constants.SPEECH_ENABLE, enable);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(MyEvent event) {
        String tag = event.getTag();
        Object data = event.getData();
        switch (tag) {
            case Constants.SPEECH_ENABLE:
                if ((boolean) data) {
                    mSpeechEnable = true;
                } else {
                    mSpeechEnable = false;

                }
                break;
        }

    }

    /*******************悬浮球end***************************/

    public int CheckRule(int seed) {
        int oldbit = 0;
        int cnt_1 = 0;  //1累计

        for (int i = 0; i < 16; i++) {
            if ((seed & 0x01) != 0) {
                cnt_1++;
            }
            if ((oldbit & (seed & 0x01)) != 0) {
                return 0;           //连续1 超过2个，ng
            }
            oldbit = seed & 0x01;           //保存上一bit
            seed >>= 1;
        }
        if (cnt_1 < 2)

        {
            return 0;          // 少于2个1，ng
        }
        return 1;

    }


    public boolean isServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.newenergy.wisehome.services.BDService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }


    public void DeleteDefaultFamily() {
        FamilyDao familyDao = new FamilyDao(this);
        BallLightDao ballLightDao = new BallLightDao(this);
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(this);
        //此标志位判断是否有用户自己创建的家庭
        boolean isOwnCreate = false;
        //当前家庭
        Family currFamily = AppManager.getInstance(this).mCurrFamily;

        //查找数据库中是否有默认家庭
        Family defaultFamily = familyDao.getById("12345678");
        if (defaultFamily != null) {

            //根据家庭码删除里面的灯组
            List<BallLight> familyBallLights = ballLightDao.getFamilyBallLights("12345678", 1);
            if (familyBallLights != null) {
                ballLightDao.delete(familyBallLights);
            }

            //根据家庭码删除里面的灯组和小家电组
            List<DeviceCategory> familyDeviceCategorys = deviceCategoryDao.getFamilyDeviceCategorys("12345678");
            if (familyDeviceCategorys != null) {
                deviceCategoryDao.delete(familyDeviceCategorys);
            }
            //从数据库中删除该数据
            familyDao.delete(defaultFamily);

        }

        //删除默认家庭之后判断当前的数据库中有多少个家庭
        List<Family> familyList = familyDao.getAll();
        if (familyList != null && familyList.size() > 0) {
            //判断是否有用户自己创建的家庭
            for (Family family:familyList) {
                if (family.getType() == 1) {//1代表有，有即跳出循环
                    isOwnCreate = true;
                    break;
                }
            }
            if (!isOwnCreate) {//有自己创建的家庭，将集合中的第一个家庭设置为当前家庭,不管是自己创建的还是分享过来的
                CreatDefault();

            }

            if (currFamily.getFamilyId().equals("12345678")) {
                    AppManager.getInstance(this).mCurrFamily= familyList.get(0);
                    SPUtil.put("FAMILY_ID", AppManager.getInstance(this).mCurrFamily.getFamilyId());
            }

//            if (isOwnCreate) {//有自己创建的家庭，将集合中的第一个家庭设置为当前家庭,不管是自己创建的还是分享过来的
//                if (currFamily.getFamilyId().equals("12345678")) {
//                    AppManager.getInstance(this).mCurrFamily= familyList.get(0);
//                }
//            }else {//没有自己的创建家庭自动给用户创建一个家庭
//                if (currFamily.getFamilyId().equals("12345678")) {
//                    AppManager.getInstance(this).mCurrFamily= familyList.get(0);
//                }
//                CreatDefault();
//            }

        }else {
            //重新给用户创建一个家庭
            AppManager.getInstance(this).mCurrFamily =  CreatDefault();
            SPUtil.put("FAMILY_ID", AppManager.getInstance(this).mCurrFamily.getFamilyId());
        }

    }


    public void showTipDialog(String content){
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessageSize(20);
        builder.setTitle(R.string.tips);
        builder.setMessage(Html.fromHtml(content));
        builder.setPositiveButton(null, (dialog1, which) -> {

        });

        builder.setNegativeButton(null, (dialog, which) -> {

        });

        mCustomDialog = builder.create();
        mCustomDialog.setCanceledOnTouchOutside(true);
        mCustomDialog.show();
    }


    public void dissDialog() {
        if (mCustomDialog != null) {
            mCustomDialog.dismiss();
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("save_allLight",AppManager.getInstance(this).mAllGroup);
        outState.putParcelable("save_selectGroup",AppManager.getInstance(this).selectGroup);
        outState.putParcelable("save_defaultBallLight",AppManager.getInstance(this).mDefaultBallLight);
        outState.putBoolean("is_controlall",AppManager.getInstance(this).isControlAll);
        outState.putInt("save_mGroupIndex",AppManager.getInstance(this).mGroupIndex);
        outState.putInt("save_mHEAIndex",AppManager.getInstance(this).mHEAIndex);

    }


    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        AppManager.getInstance(this).mAllGroup =(BallLight) savedInstanceState.getParcelable("save_allLight");
        AppManager.getInstance(this).selectGroup =(BallLight) savedInstanceState.getParcelable("save_selectGroup");
        AppManager.getInstance(this).mDefaultBallLight =(BallLight) savedInstanceState.getParcelable("save_defaultBallLight");
        AppManager.getInstance(this).isControlAll =(boolean) savedInstanceState.getBoolean("is_controlall");
        AppManager.getInstance(this).mGroupIndex =(int) savedInstanceState.getInt("save_mGroupIndex");
        AppManager.getInstance(this).mHEAIndex =(int) savedInstanceState.getInt("save_mHEAIndex");
    }


}